/**
*  Java version find
*
*       chuan.dou@accesschina.com.cn
*/

import java.io.File;
import java.io.FileFilter;
import java.util.*;

public class Find {

    //test begin...
    /*
    public static final void main(String[] args) {
        Find find = new Find("android", ".class");

        
        find.doFind();
        List r = find.findResult();

        Iterator<String> iter = r.iterator();
        while( iter.hasNext() ) {
            String path = iter.next(); 
            System.out.println(path);
        }
        
    }
    */
    //test end...

    /*
     * new Find("android", ".class");
     *
     * i need all *.class in "android" dir
     */
    public Find(String dir, final String filter) {
        this.rootDir = new File(dir);
        this.rootDirPos = rootDir.getAbsolutePath().length() + 1;

        this.fileFilter = new FileFilter() {
            public boolean accept(File f) {
                String pathName = f.getName();
                return f.isFile() && pathName.endsWith(filter);
            }
        };

        this.dirFilter = new FileFilter() {
            public boolean accept(File f) {
                return f.isDirectory();
            }
        };
    }

    public void doFind() {
        findImpl(rootDir);
    }

    public List<String> findResult() {
        return result;
    }

    private void findImpl(File fdir) {
        File []files = fdir.listFiles(fileFilter);
        File []dirs = fdir.listFiles(dirFilter);

        for(File f: files) {
            String name = f.getAbsolutePath();
            result.add(name.substring(rootDirPos));
        }

        for(File f: dirs)
            findImpl(f);
    }

    private int rootDirPos;
    private File rootDir;
    private FileFilter fileFilter;
    private FileFilter dirFilter;
    private List<String> result = new LinkedList<String>();
}
